/**
 * Project Name:javaBaseReview
 * Package Name:com.xuwei.base.queue
 * author:David
 * Date:2015年6月14日上午10:39:53
 * Copyright (c) 2015, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.base.queue;

import com.xuwei.ext.exception.QueueEmptyException;

/**
 * Queue的链式存储实现
 * @author David
 * @since 2015年6月14日 上午10:39:53
 * @version 
 * @since JDK 1.6
 */
public class QueueLink implements Queue {
	private LNode front;
	private LNode rear;
	private int size;
	
	public QueueLink() {
		front=new LNode();
		rear=front;
		size=0;
	}

	@Override
	public int getSize() {
		return size;
	}

	@Override
	public boolean isEmpty() {
		return size==0;
	}

	@Override
	public void enqueue(Object e) {
		LNode p=new LNode();
		p.setData(e);
		p.setNext(null);
		rear.setNext(p);
		rear=p;
		size++;
	}

	@Override
	public Object dequeue() throws QueueEmptyException {
		if(size<1){
			throw new QueueEmptyException("错误：队列为空！");
		}
		LNode p=front.getNext();
		front.setNext(p.getNext());
		size--;
		if(size<1){
			rear=front;//如果队列为空，rear指向头结点
		}
		return p.getData();
	}

	@Override
	public Object peek() throws QueueEmptyException {
		if(size<1){
			throw new QueueEmptyException("错误：队列为空！");
		}
		return front.getNext().getData();
	}
	
	public static void main(String[] args) {
		QueueLink link=new QueueLink();
		System.out.println("-----------------");
		System.out.println(link.getSize());
//		System.out.println(link.peek());
		System.out.println("-----------------");
		link.enqueue(9);
		link.enqueue(2);
		link.enqueue(5);
		System.out.println(link.getSize());
		System.out.println(link.peek());
		System.out.println("-----------------");
		link.dequeue();
		link.dequeue();
		System.out.println(link.getSize());
		System.out.println(link.peek());
	}

}

class LNode{
	private Object data;
	private LNode next;
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public LNode getNext() {
		return next;
	}
	public void setNext(LNode next) {
		this.next = next;
	}
	
}





